package realizeBockingQueue;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: lishuo
 * Date: 2023-04-02
 * Time: 11:20
 */

// 通过Java提供的BlockingQueue来实现 “生产者消费者模型”
public class TestBlockingQueue {
    public static void main(String[] args) {
        // 两种方式使用Java库中的阻塞队列：
        BlockingQueue<Integer> blockingQueue = new LinkedBlockingQueue<>();
        // BlockingQueue<Integer> blockingQueue1 = new ArrayBlockingQueue<Integer>(10);

        //消费者
        Thread t1 = new Thread(()->{
           while (true) {
               try {
                   int value = blockingQueue.take();
                   System.out.println("消费元素："+value);
               } catch (InterruptedException e) {
                   e.printStackTrace();
               }
           }
        });

        //生产者
        Thread t2 = new Thread(()->{
            int value = 0;
            while (true) {
                try {
                    blockingQueue.put(value);
                    System.out.println("生产元素："+value);
                    value++;
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        t1.start();
        t2.start();
        // 上述代码, 让生产者, 每隔 1s 生产一个元素.
        // 让消费者则直接消费, 不受限制.

    }
}
